package cn.edu.jsu.zjj.controller;


import cn.edu.jsu.zjj.annotation.AuthCheck;
import cn.edu.jsu.zjj.annotation.Type;
import cn.edu.jsu.zjj.common.DeleteRequest;
import cn.edu.jsu.zjj.common.result.Result;
import cn.edu.jsu.zjj.constant.MessageConstant;
import cn.edu.jsu.zjj.constant.UserConstant;
import cn.edu.jsu.zjj.exception.BaseException;
import cn.edu.jsu.zjj.exception.ThrowUtils;
import cn.edu.jsu.zjj.mapper.SysHeaderMapper;
import cn.edu.jsu.zjj.model.dto.docu.DocuAddMyRequest;
import cn.edu.jsu.zjj.model.dto.header.HeaderAddRequest;
import cn.edu.jsu.zjj.model.entity.Docu;
import cn.edu.jsu.zjj.model.entity.SysData;
import cn.edu.jsu.zjj.model.entity.SysHeader;
import cn.edu.jsu.zjj.model.utils.ZipUtils;
import cn.edu.jsu.zjj.service.ISysDataService;
import cn.edu.jsu.zjj.service.ISysHeaderService;
import cn.edu.jsu.zjj.service.UserService;
import cn.hutool.json.JSONObject;
import cn.hutool.json.JSONUtil;
import cn.zhxu.bs.BeanSearcher;
import cn.zhxu.bs.util.MapUtils;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.toolkit.StringUtils;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;

import org.springframework.stereotype.Controller;

import java.time.LocalDateTime;
import java.util.*;

import static cn.hutool.core.bean.BeanUtil.isEmpty;
import static cn.hutool.core.bean.BeanUtil.isNotEmpty;

/**
 * <p>
 * 表头相关接口
 * </p>
 *
 * @author fyt
 * @since 2024-06-12
 */
@RestController
@RequestMapping("/header")
@Slf4j
@Api(tags = "表头管理接口")
public class SysHeaderController {
    @Autowired
    private ISysHeaderService sysHeaderService;
    @Autowired
    private SysHeaderMapper sysHeaderMapper;
    @Autowired
    private BeanSearcher beanSearcher;
    @Autowired
    private UserService userService;

    @Autowired
    private ISysDataService sysDataService;

    /**
     * 根据资料id新增表头,排除已经删除还能新增表头
     *
     * @param headerAddRequest
     * @return
     */
    @ApiOperation("根据资料id新增表头")
    @PostMapping
    public Result save(@RequestBody HeaderAddRequest headerAddRequest) {
        log.info("根据资料id新增表头：{}", headerAddRequest);

        if (headerAddRequest.getSort() == null || (headerAddRequest.getName()) == null) {
            throw new BaseException(MessageConstant.SORT_NULL + "或" + MessageConstant.HEAD_NULL);
        }
        int sort = headerAddRequest.getSort();

        SysHeader oldHeader = beanSearcher.searchFirst(SysHeader.class, MapUtils.builder().field(SysHeader::getSort, sort).field(SysHeader::getIsDelete, 0).field(SysHeader::getDocuId, headerAddRequest.getDocuId()).build());
        if (oldHeader != null) {
            throw new BaseException("序号重复");
        }

        SysHeader header = new SysHeader();
        header.setUserId(userService.getLoginUser().getId());
        header.setUserName(userService.getLoginUser().getName());
        BeanUtils.copyProperties(headerAddRequest, header);
        header.setHeaderKey("key" + header.getSort());
        boolean result = sysHeaderService.save(header);
        ThrowUtils.throwIf(!result, MessageConstant.OPERATION_ERROR);
        return Result.success("新增成功");
    }

    /**
     * TODO:修改表头对应的资料并未同步修改
     *
     * @param headerAddRequest
     * @return
     */
    @ApiOperation("修改表头")
    @PutMapping
    public Result update(@RequestBody HeaderAddRequest headerAddRequest) {
        log.info("修改表头：{}", headerAddRequest);
        int sort = headerAddRequest.getSort();
        Long docuId = headerAddRequest.getDocuId();
        SysHeader oldHeader = sysHeaderMapper.selectOne(new LambdaQueryWrapper<SysHeader>().eq(SysHeader::getSort, sort).eq(SysHeader::getDocuId, docuId));
        if (oldHeader != null && oldHeader.getId().longValue() != headerAddRequest.getId().longValue()) {
            throw new BaseException("序号重复");
        }
        // 判断是否修改了表头名
        LambdaQueryWrapper<SysHeader> queryWrapper = new LambdaQueryWrapper<>();
        queryWrapper.eq(SysHeader::getDocuId, docuId);
        queryWrapper.ne(SysHeader::getIsDelete, 1);
        queryWrapper.eq(SysHeader::getId, headerAddRequest.getId());
        SysHeader sysHeader = sysHeaderMapper.selectOne(queryWrapper);
        String oldHeaderKey = "";
        if (sysHeader != null) {
            oldHeaderKey = sysHeader.getHeaderKey();
        }
        SysHeader header = new SysHeader();
        header.setUserId(userService.getLoginUser().getId());
        header.setUserName(userService.getLoginUser().getName());
        header.setUpdateTime(LocalDateTime.now());
        BeanUtils.copyProperties(headerAddRequest, header);
        String newHeaderKey = "key" + header.getSort();
        header.setHeaderKey(newHeaderKey);

        // 同步修改表格数据
        LambdaQueryWrapper<SysData> queryWrapper1 = new LambdaQueryWrapper<SysData>();
        queryWrapper1.eq(SysData::getDocuId, headerAddRequest.getDocuId());
        queryWrapper1.ne(SysData::getIsDelete, 1);

        List<SysData> sysDataList = sysDataService.list(queryWrapper1);
        for (SysData sysData : sysDataList) {
            JSONObject jsonObject = JSONUtil.parseObj(sysData.getData());
            if (jsonObject.containsKey(oldHeaderKey)) {
                log.info("修改表头对应的资料数据：{}", jsonObject);
                if (jsonObject.containsKey(newHeaderKey)) {
                    return Result.error("该表头已存在");
                }
                // 获取旧键的值
                Object oldValue = jsonObject.get(oldHeaderKey);
                // 删除旧键
                jsonObject.remove(oldHeaderKey);
                // 添加新键
                jsonObject.putOnce(newHeaderKey, oldValue);
                // 将更新后的 jsonObject 转换回字符串
                sysData.setData(jsonObject.toString());
                // 保存更新后的 sysData
                sysDataService.updateById(sysData);
            } else {
                log.warn("未找到旧的表头键：{}", oldHeaderKey);
            }
        }

        boolean result = sysHeaderService.updateById(header);

        ThrowUtils.throwIf(!result, MessageConstant.OPERATION_ERROR);
        return Result.success();
    }




    /**
     * 根据资料id查询表头,添加一个删除标志位
     *
     * @param id
     * @return
     */
    @ApiOperation("根据资料id查询表头")
    @GetMapping("/{id}")
    public Result<List<SysHeader>> getById(@PathVariable Long id) {
        log.info("根据id查询资料：{}", id);
        if (id <= 0) {
            throw new BaseException(MessageConstant.PARAMS_ERROR);
        }
        QueryWrapper<SysHeader> wrapper = new QueryWrapper<>();
        wrapper.eq("is_delete", 0);
        wrapper.eq("docu_id", id);
        wrapper.orderBy(true, true, "sort");
        return Result.success(sysHeaderMapper.selectList(wrapper));
    }

    /**
     * 根据表头id查询表头,排除删除还能查询到表头
     *
     * @param id
     * @return
     */
    @ApiOperation("根据表头id查询表头")
    @GetMapping("/detail/{id}")
    public Result<SysHeader> getDetailById(@PathVariable Long id) {
        log.info("根据id查询表头：{}", id);
        if (id <= 0) {
            throw new BaseException(MessageConstant.PARAMS_ERROR);
        }
        LambdaQueryWrapper<SysHeader> wrapper = new LambdaQueryWrapper<>();
        wrapper.eq(SysHeader::getId, id);
        wrapper.ne(SysHeader::getIsDelete, 1);
        return Result.success(sysHeaderMapper.selectOne(wrapper));
    }

    /**
     * 删除表头
     *
     * @param deleteRequest
     * @return
     */
    @Type("删除表头")
    @PostMapping("/delete")
    @ApiOperation("删除表头")
//    public Result deleteUser(@RequestBody DeleteRequest deleteRequest) {
//        log.info("删除资料：{}", deleteRequest);
//        if (deleteRequest == null || deleteRequest.getId() <= 0) {
//            throw new BaseException(MessageConstant.PARAMS_ERROR);
//        }
//        boolean b = sysHeaderService.removeById(deleteRequest.getId());
//        return Result.success(b);
//    }
    public Result deleteHeader(@RequestBody DeleteRequest deleteRequest) {
        log.info("删除资料：{}", deleteRequest);
        if (deleteRequest == null || deleteRequest.getId() <= 0) {
            throw new BaseException(MessageConstant.PARAMS_ERROR);
        }
        SysHeader header = new SysHeader();
        header.setId(deleteRequest.getId());
        header.setIsDelete(1);
        boolean result = sysHeaderService.updateById(header);
        ThrowUtils.throwIf(!result, MessageConstant.OPERATION_ERROR);
        return Result.success();
    }
}
